import os  # 新增文件操作模块

import pandas as pd
import requests


def get_weather_data(area_id, year, month):
    """获取指定地区、年份、月份的历史天气数据"""
    url = "https://tianqi.2345.com/Pc/GetHistory"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        "Referer": f"https://tianqi.2345.com/wea_history/{area_id}.htm"
    }
    params = {
        "areaInfo[areaId]": area_id,
        "areaInfo[areaType]": 2,  # 2表示城市
        "date[year]": year,
        "date[month]": month
    }

    try:
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()
        return response.json()
    except Exception as e:
        print(f"请求失败: {e}")
        return None


def parse_weather_data(json_data):
    """解析返回的JSON数据"""
    if not json_data or 'data' not in json_data:
        print("未获取到有效数据")
        return None

    # 使用pandas解析HTML表格
    try:
        tables = pd.read_html(json_data['data'])
        if not tables:
            print("未找到表格数据")
            return None

        df = tables[0]
        # 清理数据
        df.columns = ['日期', '最高温', '最低温', '天气', '风向风力', '空气质量']

        # 过滤无效行
        df = df[df['日期'].str.contains('-')]

        # 处理日期格式，只保留年-月-日
        df['日期'] = df['日期'].str.extract('(\d+-\d+-\d+)')

        # 处理温度数据
        df['最高温'] = df['最高温'].str.replace('°', '').str.extract('(\d+)')[0]
        df['最低温'] = df['最低温'].str.replace('°', '').str.extract('(\d+)')[0]

        # 只保留需要的列
        df = df[['日期', '最高温', '最低温']]

        return df
    except Exception as e:
        print(f"解析数据失败: {e}")
        return None


def save_to_excel(df, filename):
    """保存数据到Excel文件（自动创建目录）"""
    # 创建目标目录（如果不存在）
    dir_name = os.path.dirname(filename)
    if dir_name and not os.path.exists(dir_name):
        os.makedirs(dir_name)

    try:
        df.to_excel(filename, index=False, engine='openpyxl')
        print(f"数据已保存到 {filename}")
    except Exception as e:
        print(f"保存文件失败: {e}")


if __name__ == "__main__":
    # 地区ID # 桂林57957 # 柳州59046 # 贺州59065
    print("请输入地区（1：桂林，2：柳州，3：贺州）")
    area_id = 0
    city_name = ''
    id = int(input())
    if id == 1:
        area_id = "57957"
        city_name = 'guilin'
    elif id == 2:
        area_id = "59046"
        city_name = 'liuzhou'
    elif id == 3:
        area_id = "59065"
        city_name = 'hezhou'

    print('请输入年份')
    year = input()
    print('请输入月份')
    month = input()

    # 获取数据
    weather_json = get_weather_data(area_id, year, month)

    if weather_json:
        # 解析数据
        weather_df = parse_weather_data(weather_json)

        if weather_df is not None:
            # 构造带目录的文件名
            filename = f"./{city_name}/{year}年{month}月.xlsx"
            save_to_excel(weather_df, filename)
            # 打印前5行数据
            print("\n获取到的天气数据样例:")
            print(weather_df.head())
